package com.finger.forest;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.FileModel;
import com.finger.forest.model.ResourceModel;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.VoiceWidthUtil;
import com.finger.forest.utils.record.AudioRecorder;
import com.loopj.android.image.SmartImageView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static android.view.View.generateViewId;

/**
 * 资源详情信息
 */
public class CollectionResourceDetailInfoActivity extends BaseActivity<RegisterPresenter> implements View.OnClickListener, BaseView {

    private static final String TAG = "CollectionResourceDIAct";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    /**
     * 存放拍照图片布局
     */
    @BindView(R.id.layout_photo)
    LinearLayout photoLayout;

    /**
     * 位置
     */
    @BindView(R.id.layout_location)
    LinearLayout locationLayout;

    /**
     * 类型
     */
    @BindView(R.id.layout_type)
    LinearLayout typeLayout;

    /**
     * 存放录音布局
     */
    @BindView(R.id.layout_sound)
    LinearLayout soundLayout;

    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.tvLocation)
    TextView tvLocation;

    @BindView(R.id.etTypeName)
    EditText etTypeName;
    @BindView(R.id.etRemark)
    EditText etRemark;

    private ArrayList<String> picFileList = new ArrayList<>();

    AudioRecorder audioRecorder;
    LayoutInflater factory = null;

    @Override
    protected int setView() {
        return R.layout.activity_collection_resource_detail_info;
    }

    @Override
    protected void receiveData() {
        Intent intent = getIntent();
        int id = intent.getIntExtra("id",0);
        Map<String,Object> mapParams = new HashMap<>();
        mapParams.put("id",id);
        //查询资源详情
        presenter.queryResourceDetail(mapParams);
    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static final int REQUEST_EXTERNAL_STORAGE2 = 2;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO};

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    @Override
    protected void initializeView() {

        verifyStoragePermissions(CollectionResourceDetailInfoActivity.this);

        audioRecorder = AudioRecorder.getInstance();
        factory = LayoutInflater.from(CollectionResourceDetailInfoActivity.this);

    }

    @Override
    protected void loadDataFromServer() {

    }

    @OnClick({R.id.btn_back})
    @Override
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //点击查看图片
                case R.id.iv_photo:
                    Log.i(TAG,"图片Position："+ v.getTag());
                    Intent intent = new Intent(CollectionResourceDetailInfoActivity.this, PhotoViewActivity.class);
                    intent.putExtra("currentPosition",Integer.parseInt(v.getTag().toString()));
                    intent.putStringArrayListExtra("picFileList",picFileList);
                    startActivity(intent);
                    break;

                //点击播放语音
                case R.id.tv_sound_record_item:
                    Log.i(TAG,"语音URL："+ v.getTag());

                    MediaPlayer mediaPlayer = new MediaPlayer();
                    mediaPlayer.reset();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    try {
                        mediaPlayer.setDataSource(v.getTag().toString()+"");
                        mediaPlayer.prepare();
                        mediaPlayer.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {

            case ResponseTag.QUERY_RESOURCE_DETAIL:
                ResourceModel resourceModel = (ResourceModel) model;
                if (resourceModel != null){
                    Log.i(TAG, resourceModel.getName());
                    tvLocation.setText(resourceModel.getLongitude() + "," + resourceModel.getLatitude());
                    tvType.setText(resourceModel.getResouTypeName()==null?"":resourceModel.getResouTypeName());
                    etTypeName.setText(resourceModel.getName());
                    etRemark.setText(resourceModel.getRemark()==null?"":resourceModel.getRemark());

                    List<FileModel> fileDataList = resourceModel.getDataFile();
                    LayoutInflater factory = LayoutInflater.from(CollectionResourceDetailInfoActivity.this);
                    for (FileModel fileModel:fileDataList){
                        int fileType = fileModel.getFileType();
                        String filePath = fileModel.getFilePath();
                        if (fileType == 3){//图片
                            View layout = factory.inflate(R.layout.url_photo_item, null);
                            RelativeLayout photoItemLayout = (RelativeLayout) layout.findViewById(R.id.layout_photo_item);//布局
                            photoItemLayout.setId(generateViewId());
                            SmartImageView photoIv = (SmartImageView) layout.findViewById(R.id.iv_photo);//图片
                            photoIv.setTag(picFileList.size());
                            photoIv.setImageUrl(filePath);
                            photoLayout.addView(photoItemLayout);

                            photoIv.setOnClickListener(this);
                            picFileList.add(filePath);//将图片文件添加到图片集合
                        } else if (fileType == 4){//语音

                            View layout = factory.inflate(R.layout.url_sound_item, null);
                            RelativeLayout soundItemLayout = (RelativeLayout) layout.findViewById(R.id.layout_sound_item);//布局
                            ImageView soundRecordTv = (ImageView) layout.findViewById(R.id.tv_sound_record_item);//语音气泡
                            soundRecordTv.setTag(filePath);
                            ViewGroup.LayoutParams soundRecordTv_params = soundRecordTv.getLayoutParams();
                            soundRecordTv_params.width = VoiceWidthUtil.calVoiceWidth1(fileModel.getFileSize());//计算气泡宽度
                            soundRecordTv.setLayoutParams(soundRecordTv_params);//设置语音气泡宽度

                            soundRecordTv.setOnClickListener(this);
                            soundLayout.addView(soundItemLayout);
                        }
                    }
                }
                break;

            default:
                break;
        }

        hidePd();
    }

    @Override
    public void onError(int errcode, int tag, String message) {
        ToastUtils.show(message);
        hidePd();
    }
}
